import tornado.ioloop
from domain.girls.girls_api  import GirlsHandler
from domain.girls.girls_api import LoginHandler
from domain.activity.activity_api import ActivityHandler
from domain.activity.activity_api import ActivityTypeFavListHandler
from domain.activity.activity_api import ActivityStartHandler
from domain.activity.activity_api import ActivityCancelHandler
from domain.activity.activity_api import ActivityFinishListHandler
from domain.address.address_api import AddressHandler
from domain.chatroom.chatroom_api import ChatRoomHandler
from domain.comment.comment_api import CommentHandler
from domain.fav.fav_api import FavHandler
from domain.reg.reg_api import UserRegHandler
from domain.message.message_api import MessageUnreadCountHandler
from domain.message.message_api import MessageListHandler
from domain.auth.auth_api import UserAuthHandler
from infra.file import UploadFileHandler
# from tornado.web import StaticFileHandler
from common.backup import backup_database
from common.config import cfg
from common.log import access_logger
from common.log import app_logger
from common.finish_activity import ActivityAutoFinishHandler

def make_app():
    return tornado.web.Application([
        (r"/api/girls/login", LoginHandler),
        (r"/api/girls/girls", GirlsHandler),
        (r"/api/activity/activity", ActivityHandler),
        (r"/api/activity/activity/start", ActivityStartHandler),
        (r"/api/activity/activity/cancel", ActivityCancelHandler),
        (r"/api/activity/activity_type", ActivityTypeFavListHandler),
        (r"/api/activity/activity_finish", ActivityFinishListHandler),
        (r"/api/chatroom/chatroom", ChatRoomHandler),
        (r"/api/activity/address", AddressHandler),
        (r'/api/infra/file',UploadFileHandler),
        (r"/api/comment/comment", CommentHandler),
        (r"/api/fav/fav", FavHandler),
        (r"/api/reg/reg", UserRegHandler),
        (r"/api/message/message_unread_count", MessageUnreadCountHandler),
        (r"/api/message/message", MessageListHandler),
        (r"/api/auth/auth", UserAuthHandler),
        # (r"/(.*)", StaticFileHandler, {"path": cfg['front-end']['basedir'], "default_filename": cfg['front-end']['default']}),
    ], login_url="/")

if __name__ == "__main__":
 
    app = make_app()
    app.users = {}
    app.listen(cfg['port'])
    # Schedule the backup task to run every hour
    if cfg['backup']['enable']:
        scheduler = tornado.ioloop.PeriodicCallback(backup_database, cfg['backup']['interval'] * 60 * 1000)
        scheduler.start()
        app_logger.info("backup started")
    auto_finish_handler = ActivityAutoFinishHandler()
    # 创建定时任务执行异步
    auto_finish_scheduler = tornado.ioloop.PeriodicCallback(
        auto_finish_handler.check_and_finish_activities,
        1 * 60 * 1000  # 5 minutes in milliseconds
    )
    auto_finish_scheduler.start()
    app_logger.info("activity auto finish checker started")
    tornado.ioloop.IOLoop.current().start()

